<template>
  <div>
    <el-drawer
      v-model="visible"
      :title="props.title"
      :size="props.width"
      :before-close="hide"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :modal="true"
    >
      <template #title>
        <div class="flex flex-col">
          <div class="drawer-header">
            <div class="flex items-center dot" v-if="showDot">
              <div class="w-[5px] h-[5px] rounded-1/2 bg-[#3721FF]"></div>
              <span class="ml-2 drawer-title">{{ props.title }}</span>
            </div>
          </div>
          <div class="text-[12px] mt-[4px] text-[#999] desc">{{ props.titleDesc }}</div>
        </div>
      </template>
      <div class="drawer-content mt--4">
        <slot></slot>
        <div class="flex">
          <div
            class="drawer-content-item border border-solid border-[#eee] p-4 rounded-2 w-[200px] mt-2"
          >
            <h4 v-if="props.templateType != '1'">模板功能</h4>
            <el-form
              label-width="100px"
              :model="templateForm"
              ref="dataFormRef"
              :rules="templateRules"
              class="w-[100%] mt-4"
              label-position="top"
            >
              <el-form-item label="落地页形态" prop="rollType" v-if="props.templateType != '1'">
                <el-radio-group v-model="templateForm.landingPageForm" @change="changePageForm">
                  <template v-for="(item, index) in loadingPageFormType" :key="index">
                    <el-radio :label="item.label" :value="item.value">{{ item.label }}</el-radio>
                  </template>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="营销功能" prop="rollType" v-if="props.templateType != '1'">
                <el-checkbox-group
                  v-model="templateForm.marketingFeatures"
                  @change="changeMarketingFeatures"
                >
                  <template v-for="(item, index) in marketingFeaturesType" :key="index">
                    <el-checkbox :label="item.value" :value="item.value">
                      {{ item.label }}
                    </el-checkbox>
                  </template>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="模板介绍">
                <div>
                  <p class="flex flex-col text-[12px]">
                    <span>推荐场景</span>
                    <span>{{
                      slectTemplate?.recommendedScenario ? slectTemplate?.recommendedScenario : '-'
                    }}</span>
                  </p>
                  <p class="flex flex-col text-[12px]">
                    <span>具备营销功能</span>
                    <span>{{
                      slectTemplate?.marketingFeatures ? slectTemplate?.marketingFeatures : '-'
                    }}</span>
                  </p>
                  <p class="flex flex-col text-[12px]" v-if="props.templateType != '1'">
                    <span>适用端口</span>
                    <span>{{
                      slectTemplate?.applicablePorts ? slectTemplate?.applicablePorts : '-'
                    }}</span>
                  </p>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div v-loading="loading">
            <div class="flex flex-wrap" >
              <!-- 商品模板展示 -->
              <div v-if="props.templateType != '1'" class="flex flex-wrap ml-2">
                <div 
                  class="template-item w-[200px] h-[300px] m-2 rounded-4 overflow-hidden cursor-pointer"
                  v-for="(itm, idx) in templateList"
                  :key="idx"
                  :class="{ 'template-item-selected': selectedTemplate === itm.id }"
                  @click="selectTemplate(itm)"
                  @mouseenter="hoverIndex = idx"
                  @mouseleave="hoverIndex = null"
                >
                  <div class="w-[100%] h-[100%] relative template-item-img">
                    <div class="w-[100%] h-[100%]">
                      <img :src="itm.previewPicUrls" alt="" class="w-[100%] h-[100%] object-cover" />
                      <!-- 蒙层（只在hover时显示） -->
                      <div
                        v-if="hoverIndex === idx"
                        class="absolute inset-0 transition-all duration-300 bg-black bg-opacity-50"
                      ></div>
                    </div>
                    <div class="absolute top-2 left-2 w-[100%] h-[30px]" v-if="itm.isTop == 0">
                      <el-button class="" size="small" color="#3721FF" plain>置顶</el-button>
                    </div>
                    <div class="absolute top-2 right-2 w-[30px] h-[30px] btn">
                      <Icon
                        v-if="selectedTemplate === itm.id"
                        icon="material-symbols:check-box-outline"
                        :size="24"
                        color="#3721FF"
                      />
                      <Icon v-else icon="material-symbols-light:check-box-outline-blank" :size="24" />
                    </div>
                    <div class="absolute bottom-2 right-2 w-[100%] h-[30px] btn">
                      <span
                        class="img-btn text-[12px] bg-[#fff] pt-4px pl-1 pr-1 rounded-4px mr-2"
                        @click.stop="stopPropagation(itm)"
                      >
                        <Icon icon="weui:eyes-on-outlined" :size="14" />
                      </span>
                      <span
                        class="img-btn text-[12px] bg-[#fff] pt-4px pl-1 pr-1 rounded-4px"
                        @click.stop="handleTopPosition(itm)"
                      >
                        <Icon icon="material-symbols:vertical-align-top" :size="14" />
                      </span>
                    </div>
                  </div>
                  <p
                    class="absolute m-auto text-center text-[14px] pt-2"
                    style="margin: 0 auto; width: inherit"
                    >{{ itm.name }}</p
                  >
                </div>
              </div>
              <!-- 网站模板展示 -->
              <div v-else class="h-[800PX] relative">
                <div  class="relative " v-for="(itm, idx) in templateList"
                   :key="idx">
                  <div 
                   class="template-item template-item-type1 w-[1000px] mb-8 m-2 rounded-4 overflow-hidden cursor-pointer relative"
                  
                   :class="{ 'template-item-selected': selectedTemplate === itm.id }"
                   @click="selectTemplate(itm)"
                   @mouseenter="hoverIndex = idx"
                   @mouseleave="hoverIndex = null"
                 >
                   <div class="w-[100%] h-[100%] relative template-item-img">
                     <div class="w-[100%] h-[100%]">
                       <img :src="itm.previewPicUrls" alt="" class="w-[100%] h-[100%] object-cover" />
                       <!-- 蒙层（只在hover时显示） -->
                       <div
                         v-if="hoverIndex === idx"
                         class="absolute inset-0 transition-all duration-300 bg-black bg-opacity-50"
                       ></div>
                     </div>
                     <div class="absolute top-2 left-2 w-[100%] h-[30px]" v-if="itm.isTop == 0">
                       <el-button class="" size="small" color="#3721FF" plain>置顶</el-button>
                     </div>
                     <div class="absolute top-2 right-2 w-[30px] h-[30px] btn">
                       <Icon
                         v-if="selectedTemplate === itm.id"
                         icon="material-symbols:check-box-outline"
                         :size="24"
                         color="#3721FF"
                       />
                       <Icon v-else icon="material-symbols-light:check-box-outline-blank" :size="24" />
                     </div>
                     <div class="absolute bottom-2 right-2 w-[100%] h-[30px] btn">
                       <span
                         class="img-btn text-[12px] bg-[#fff] pt-4px pl-1 pr-1 rounded-4px mr-2"
                         @click.stop="stopPropagation(itm)"
                       >
                         <Icon icon="weui:eyes-on-outlined" :size="14" />
                       </span>
                       <span
                         class="img-btn text-[12px] bg-[#fff] pt-4px pl-1 pr-1 rounded-4px"
                         @click.stop="handleTopPosition(itm)"
                       >
                         <Icon icon="material-symbols:vertical-align-top" :size="14" />
                       </span>
                     </div>
                   </div>
                  </div>
                  <p
                    class="absolute bottom--6 left-0 right-0 m-auto text-center text-[12px]"
                    style="margin: 0 auto; width: inherit;z-index: 1000;"
                    >{{ itm.name }}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="drawer-footer el-dia-btn">
          <el-button @click="hide">取消</el-button>
          <el-button type="primary" color="#3721FF" @click="submit">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
const emit = defineEmits(['update:visible', 'update:selectTemplate', 'selectedTemplateRes'])
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { ProductApi } from '@/api/product/addProduct'
import { getAccessToken, getTenantId } from '@/utils/auth'

const loadingPageFormType = getStrDictOptions(DICT_TYPE.PRODUCT_FORM_TYPE)
const marketingFeaturesType = getStrDictOptions(DICT_TYPE.MARKETING_FEATURES_TYPE)
// console.log(loadingPageFormType, 'tradeType') //落地页形态
// console.log(marketingFeaturesType, 'tradeType') //营销功能
const templateForm = reactive({
  landingPageForm: '', // 落地页形态
  marketingFeatures: [] // 营销功能
})
// 新增 hoverIndex 状态
const hoverIndex = ref(null)
const templateList = ref([])
const loading= ref(false)
const templateRules = reactive({
  rollType: [{ required: true, message: '请输入滚动效果', trigger: 'blur' }]
})
const props = defineProps({
  formData: {
    type: Object,
    default: () => ({})
  },
  templateType: {
    type: String
  },
  title: {
    type: String
  },
  width: {
    type: String,
    default: '50%'
  },
  showDot: {
    type: Boolean,
    default: false
  }
})
const visible = ref(false)
const slectTemplate = ref<any>(null)
const selectedTemplate = ref<string | null>(null)
const selectedTemplateRes = ref<any>(null)
// 选择模板
const changePageForm = (val) => {
  getTemplateList()
}
const selectedMarketingFeatures = ref<any>([])
const changeMarketingFeatures = (val) => {
  selectedMarketingFeatures.value = val
  getTemplateList()
}
const selectTemplate = (res) => {
  selectedTemplate.value = res.id
  selectedTemplateRes.value = res
  slectTemplate.value = res
}
const stopPropagation = (row) => {
  console.log(props.formData?.domain, 'props.formData?.domain');
  // if(Array.isArray(JSON.parse(JSON.stringify(props.formData)).domain)){
  //   if(props.formData?.domain.length == 0) {
  //     ElMessage.error('请先选择网站域名')
  //     return
  //   }
  // }else{
  //   if(props.formData?.domain){
  //     if(props.formData?.domain?.split(',').length == 0) {
  //       ElMessage.error('请先选择网站域名')
  //       return
  //     }
  //   }else {
  //     ElMessage.error('请先选择网站域名')
  //     return
  //   } 
  // }
  if(props.templateType=='2'){
  ProductApi.getProductId(row.id).then((res) => {
    console.log(JSON.parse(JSON.stringify(props.formData)).domain,'JSON.parse(JSON.stringify(props.formData)).domain');
      // window.open(
      //   'https://' +
      //    (Array.isArray(JSON.parse(JSON.stringify(props.formData)).domain) ? props.formData.domain[0] : props.formData.domain?.split(',')[0]) + 
      //    '/#/product?id=' + res + '&tenantId=' + getTenantId(),
      //   '_blank'
      // )
      window.open(
        'https://shop.dashubobo.com/#/product?id=' + res + '&tenantId=' + getTenantId(),
        '_blank'
      )
    })
  }else{
    // 需要提供一个接口
    // window.open(
    //   'https://' +
    //    (Array.isArray(JSON.parse(JSON.stringify(props.formData)).domain) ? props.formData.domain[0] : props.formData.domain?.split(',')[0]),
    //   '_blank'
    // )
    if(row.id=='60014'){
      window.open('https://shop.dashubobo.com','_blank')
    }
  }

}
const handleTopPosition = (row) => {
  ProductApi.updateTop({ id: row.id, isTop: row.isTop == 0 ? 1 : 0 }).then((res) => {
    getTemplateList()
  })
}
// 获取模板
const getTemplateList = () => {
  let newmarketingFeatures =
  selectedMarketingFeatures.value && selectedMarketingFeatures.value.length > 0
  ? selectedMarketingFeatures.value.join(',')
  : ''
  loading.value = true
  ProductApi.templatePage({
    landingPageForm: templateForm.landingPageForm == '不限' ? '' : templateForm.landingPageForm, // 落地页形态
    marketingFeatures: newmarketingFeatures,
    type: props.templateType ? props.templateType : '2',
    status: 0
  }).then((res) => {
    templateList.value = res.list
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}
const submit = () => {
  if (!selectedTemplate.value) {
    ElMessage.error('请选择模板')
    return
  }
  emit('update:selectTemplate', selectedTemplate.value)
  emit('selectedTemplateRes', selectedTemplateRes.value)
  hide()
}
const hide = () => {
  visible.value = false
}
const show = () => {
  visible.value = true
  getTemplateList()
}

watch(
  () => visible.value,
  (val) => {
    emit('update:visible', val)
  }
)
onMounted(() => {
  // getTemplateList()
})
defineExpose({
  show,
  hide
})
</script>

<style lang="scss" scoped>

.template-item {
  width: 200px;
  height: 300px;
  border: 2px solid transparent;
  transition: all 0.3s ease;
  .template-item-img {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border: 1px solid #e4e7ed;
    background: #faf7f7;
    .btn {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}
.template-item-type1{
  width: 800px;
  height: 540px;
}
.template-item-selected {
  border: 2px solid #3721ff;
  box-shadow: 0 0 0 2px rgba(55, 33, 255, 0.2);
  // transform: translateY(-2px);
}

// .template-item:hover {
//   box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
//   transform: translateY(-2px);
// }

/* 新增按钮样式 */
.img-btn {
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: #f0f0f0 !important;
    transform: scale(1.05);
  }
}
</style>
<style scoped>
@import '@/styles/theme.scss';
@import '@/styles/website.scss';
</style>
